package com.tutu.utils;

import com.tutu.entity.Image;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.imageio.ImageIO;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 图片上传工具类
 * Created by 涂奕恒 on 2017/2/15 0015.
 */
@Slf4j
public class ImageUtils {

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    public static final String uploadPath = "/webapps/files/upload";
    static final String imagePath = "images";

    public static void delete(String path) {
        try {
            if (BaseUtil.isNotBlank(path)) {
                File file = new File(ConfigUtil.getString("upload.path") + path);
                if (file.exists()) {
                    file.deleteOnExit();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存并返回图片信息
     *
     * @param file MultipartFile
     */
    public static Image saveImage(MultipartRequest multipartRequest) {
        try {
            MultipartFile file = multipartRequest.getFile("file");

            // 1. 原始文件名 & 后缀
            String original = file.getOriginalFilename();
            String ext = StringUtils.getFilenameExtension(original);
            if (!StringUtils.hasText(ext)) ext = "jpg";

            // 2. 相对路径 /upload/shop/2025/11/08/uuid.ext
            String relative = String.format("/upload/%s/%s/%s.%s", imagePath, LocalDate.now().format(DTF), UUID.randomUUID(), ext);

            // 3. 绝对路径
            Path absolute = Paths.get(uploadPath, relative);
            Files.createDirectories(absolute.getParent());

            // 4. 一次性读宽高 + 落盘（零拷贝）
            try (InputStream in = file.getInputStream()) {
                BufferedImage bi = ImageIO.read(in);   // 读取后 in 已耗尽
                if (bi == null) throw new IllegalArgumentException("非法图片");

                // 5. 重新打开流写入磁盘（Spring 的 MultipartFile 支持多次 getInputStream）
                try (InputStream in2 = file.getInputStream()) {
                    Files.copy(in2, absolute, StandardCopyOption.REPLACE_EXISTING);
                }

                Image image = new Image();

                image.setUrl(relative);
                image.setWidth(bi.getWidth());
                image.setHeight(bi.getHeight());

                return image;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Image();
    }

    /**
     * 获取项目在tomcat下的地址
     */
    public static String getWebPath(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(true);
        String path = session.getServletContext().getRealPath("/").replace(File.separator, "/");
        String[] paths = path.split("/");
        StringBuilder buff = new StringBuilder();

        for (int i = 0; i < paths.length - 1; i++)
            buff.append(paths[i]).append("/");

        return buff.toString();
    }

    public static String checkFileUrl(String path) {
        if (BaseUtil.isBlank(path)) return "";

        if (path.startsWith("http")) {
            return "/" + path;
        } else {
            return PathUtils.getRemotePath() + "/" + path;
        }
    }
}
